package com.paipaideli.common.banner;

import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.paipaideli.R;
import com.paipaideli.common.utils.DensityUtil;
import com.paipaideli.common.utils.ImageUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * banner
 */

public class BannerView extends LinearLayout {
    private ViewPager mViewPager;
    public LinearLayout mLinearLayout;
    private Context mContext;
    private ImageView[] mIndicator;
    private Handler mHandler = new Handler();
    final List<String> mList = new ArrayList<>();
    private BannerOnClickListener onClickListener;

    protected boolean isCover(View view) {
        boolean cover = false;
        Rect rect = new Rect();
        cover = view.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= view.getMeasuredWidth() && rect.height() >= view.getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mViewPager == null) {
                return;
            }
            try {
                if (!isCover(mViewPager)) {
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            mHandler.postDelayed(mRunnable, 3000);

        }
    };
    private int mItemCount;
    public BannerPagerAdapter bannerPagerAdapter;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    private void init() {
        View.inflate(mContext, R.layout.view_bannerview, this);
    }

    /**
     * 给banner中的viewpager设置数据
     *
     * @param list
     */
    public void setList(List<String> list) {
        // 取到布局中的控件
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mLinearLayout = (LinearLayout) findViewById(R.id.ll_points);
        clearAdapter();
        mList.addAll(list);
        mItemCount = mList.size();
        bannerPagerAdapter = new BannerPagerAdapter(mList, mContext);
        mViewPager.setAdapter(bannerPagerAdapter);
        initView();
    }

    private void initView() {
        // 初始化底部点指示器
        initIndicator(mList, mContext);
        mViewPager.setCurrentItem(500 * mItemCount);

        // 给viewpager设置滑动监听
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switchIndicator(position % mItemCount);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                cancelRecycle();
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                startRecycle();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initIndicator(List<String> list, Context context) {
        mIndicator = new ImageView[mItemCount];
        for (int i = 0; i < mIndicator.length; i++) {
            int i1 = DensityUtil.dip2px(context, 6);
            int ind = DensityUtil.dip2px(context, 4);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(i1, i1);
            params.setMargins(ind, 0, ind, 0);
            ImageView imageView = new ImageView(context);
            mIndicator[i] = imageView;
            if (i == 0) {
                mIndicator[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            } else {
                mIndicator[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }
            mLinearLayout.addView(imageView, params);
        }
        if (mItemCount == 1) {
            mLinearLayout.setVisibility(View.GONE);
        } else {
            mLinearLayout.setVisibility(View.VISIBLE);
        }
    }

    private void switchIndicator(int selectItems) {
        for (int i = 0; i < mIndicator.length; i++) {
            if (i == selectItems) {
                mIndicator[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            } else {
                mIndicator[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }
        }
    }

    private void startRecycle() {
        mHandler.postDelayed(mRunnable, 5000);
    }

    private void cancelRecycle() {
        mHandler.removeCallbacks(mRunnable);
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        if (visibility == VISIBLE) {
            startRecycle();
        } else {
            cancelRecycle();
        }
    }

    private class BannerPagerAdapter extends PagerAdapter {
        private List<String> imagesUrl;
        private Context context;

        public BannerPagerAdapter(List<String> imagesUrl, Context contexts) {
            this.imagesUrl = imagesUrl;
            this.context = contexts;
        }

        @Override
        public int getCount() {
            return mItemCount == 1 ? 1 : Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            try {
                View contentView = LayoutInflater.from(mContext).inflate(R.layout.view_banner_imageview, null);
                AppCompatImageView imageView = (AppCompatImageView) contentView.findViewById(R.id.iv_image1);
                try {
                    String url = imagesUrl.get(position % mItemCount);
                    ImageUtil.displayBannerImage(url, imageView);
                } catch (Exception e) {
                    e.getMessage();
                }
                if (onClickListener != null) {
                    if (imageView != null) {
                        imageView.setOnClickListener(view -> onClickListener.onClickListener(position % mItemCount));
                    }
                }
                container.addView(imageView);
                return imageView;
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (object != null) {
                container.removeView((View) object);
            }
        }
    }

    public void clearAdapter() {
        if (mList != null) {
            mList.clear();
        }
        if (mLinearLayout != null) {
            mLinearLayout.removeAllViews();
        }
        if (bannerPagerAdapter != null) {
            if (mContext != null & mList != null) {
                bannerPagerAdapter = new BannerPagerAdapter(mList, mContext);
                bannerPagerAdapter.notifyDataSetChanged();
            }
        }

    }

    /**
     * banner item的点击监听
     *
     * @param onClickListener
     */

    public void setOnClickListener(BannerOnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public interface BannerOnClickListener {
        void onClickListener(int pos);
    }

}
